<script>
import {goBack, messageTip} from "../util/util.js";
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";

export default {
  name: "CustomerDetailView",

  inject: ["reload"],

  data() {
    return {
      customerDeatil: {
        clueDO: {},
        ownerDO: {},
        activityDO: {},
        appellationDO: {},
        intentionProductDO: {},
        // 假设接口返回时包含一个标识，若已转换账单则为 true，否则为 false
        billConverted: false
      },
      // 客户备注对象（新增备注使用）
      customerRemark: {},
      // 客户备注编辑相关数据
      customerEditRemarkDialogVisible: false,
      customerEditRemarkQuery: {
        id: null,
        noteWay: null,
        noteContent: ''
      },
      customerEditRemarkRules: {
        noteWay: [
          {required: true, message: '请选择跟踪方式', trigger: ['blur', 'change']}
        ],
        noteContent: [
          {required: true, message: '跟踪内容不能为空', trigger: 'blur'},
          {min: 5, max: 500, message: '跟踪内容长度为5-500个字符', trigger: 'blur'}
        ]
      },
      // 跟踪方式下拉选项
      noteWayOptions: [{}],
      // 客户备注记录列表
      customerRemarkList: [{
        noteWayDO: {},
        createByDO: {},
        editByDO: {}
      }],
      // 分页参数
      pageSize: 0,
      total: 0,
      // 客户备注表单验证规则（新增备注）
      customerRemarkRules: {
        noteWay: [
          {required: true, message: '请选择跟踪方式', trigger: ['blur', 'change']}
        ],
        noteContent: [
          {required: true, message: '跟踪内容不能为空', trigger: 'blur'},
          {min: 5, max: 500, message: '跟踪内容长度为5-500个字符', trigger: 'blur'}
        ]
      },
      // —— 以下为转换为账单相关数据 ——
      convertBillDialogVisible: false,
      billQuery: {
        money: null,
        expectedDate: '',
        stage: null,
        description: '',
        nextContactTime: '',  // 新增字段
      },
      convertBillRules: {
        money: [{required: true, message: '请输入交易金额', trigger: 'blur'}],
        expectedDate: [{required: true, message: '请选择预计成交日期', trigger: 'change'}],
        nextContactTime: [{required: true, message: '请选择下次联系时间', trigger: 'change'}], // 校验规则
        stage: [{required: true, message: '请选择交易阶段', trigger: 'change'}],
        description: [{required: true, message: '请输入交易描述', trigger: 'blur'}]
      },
      stageOptions: [{}],
      // 标识是否已转换为账单（转换后置为 true，按钮不再显示）
      billConverted: false
    };
  },

  methods: {
    goBack,
    // 加载客户详情（假设接口返回中包含 billConverted 字段）
    loadCustomerDetail() {
      let id = this.$route.params.id;
      doGet("/api/customer/detail/" + id, {}).then(resp => {
        if (resp.data.code == 200) {
          this.customerDeatil = resp.data.data;
          // 同步转换状态
          this.billConverted = this.customerDeatil.billConverted;
        }
      });
    },
    // 加载客户备注列表（分页）
    loadCustomerRemarkList(current) {
      doGet("/api/customer/remark", {
        current: current, // 当前页
        customerId: this.$route.params.id
      }).then(resp => {
        if (resp.data.code === 200) {
          this.customerRemarkList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      });
    },
    // 加载字典数据，扩展处理 stage 类型
    loadDicValue(typeCode) {
      doGet("/api/dicvalue/" + typeCode, {}).then(resp => {
        if (resp.data.code === 200) {
          if (typeCode === 'noteWay') {
            this.noteWayOptions = resp.data.data;
          } else if (typeCode === 'product') {
            this.productOptions = resp.data.data;
          } else if (typeCode === 'stage') {
            this.stageOptions = resp.data.data;
          }
        }
      });
    },
    // 提交客户备注（新增备注）
    clueRemarkSubmit() {
      this.$refs.customerRemarkRefForm.validate(valid => {
        if (valid) {
          doPost("/api/customer/remark", {
            customerId: this.customerDeatil.id,
            noteContent: this.customerRemark.noteContent,
            noteWay: this.customerRemark.noteWay
          }).then(resp => {
            if (resp.data.code === 200) {
              messageTip("提交成功", "success");
              this.reload();
            } else {
              messageTip("提交失败", "error");
            }
          });
        }
      });
    },
    // 打开客户备注编辑弹窗（模仿线索备注编辑弹窗）
    editRemark(id) {
      // 先加载 noteWay 字典数据
      doGet("/api/dicvalue/noteWay", {}).then(resp => {
        if (resp.data.code === 200) {
          this.noteWayOptions = resp.data.data;
          this.customerEditRemarkDialogVisible = true;
          doGet("/api/customer/remark/" + id, {}).then(resp => {
            if (resp.data.code === 200) {
              this.customerEditRemarkQuery = resp.data.data;
            }
          });
        }
      });
    },
    // 提交客户备注编辑修改
    customerEditRemarkSubmit() {
      this.$refs.customerRemarkEditForm.validate(valid => {
        if (valid) {
          doPut("/api/customer/remark/update", this.customerEditRemarkQuery).then(resp => {
            if (resp.data.code === 200) {
              messageTip("修改成功", "success");
              this.customerEditRemarkDialogVisible = false;
              this.loadCustomerRemarkList(1);
            } else {
              messageTip("修改失败", "error");
            }
          });
        }
      });
    },
    // 分页函数
    toPage(current) {
      this.loadCustomerRemarkList(current);
    },
    // 删除客户备注
    delRemark(id) {
      this.$confirm('确定删除该跟踪记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        doDelete("/api/customer/remark/delete/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            this.loadCustomerRemarkList(1);
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消删除备注", "warning");
      });
    },

    // —— 转换为账单相关 ——
    // 打开转换为账单弹窗（只能转换1次）
    convertBill() {
      if (this.billConverted) {
        messageTip("已经转换为账单，不能重复转换", "warning");
        return;
      }
      this.convertBillDialogVisible = true;
      // 加载 stage 字典数据
      this.loadDicValue('stage');
    },

    // 提交转换为账单
    convertBillSubmit() {
      this.$refs.convertBillRefForm.validate(isValid => {
        if (isValid) {
          doPost("/api/customer/tran", {
            customerId: this.customerDeatil.id,
            money: this.billQuery.money,
            expectedDate: this.billQuery.expectedDate,
            stage: this.billQuery.stage,
            description: this.billQuery.description,
            nextContactTime: this.billQuery.nextContactTime
          }).then(resp => {
            if (resp.data.code === 200) {
              messageTip("转换为账单成功", "success");
              this.convertBillDialogVisible = false;
              this.billConverted = true;
            } else {
              messageTip(resp.data.msg, "error");
            }
          });
        }
      });
    }
  },

  mounted() {
    this.loadCustomerDetail();
    this.loadCustomerRemarkList(1);
  }
};
</script>

<template>
  <div>
    <!-- 客户详情展示及新增备注表单 -->
    <el-form ref="customerRemarkRefForm" :model="customerRemark" label-width="110px" :rules="customerRemarkRules"
             style="max-width: 95%;">
      <el-form-item label="负责人">
        <div class="desc">{{ customerDeatil.ownerDO.name }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="所属活动">
        <div class="desc">{{ customerDeatil.activityDO.name }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="选购产品">
        <div class="desc">{{ customerDeatil.intentionProductDO.name }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="姓名">
        <div class="desc">{{ customerDeatil.clueDO.fullName }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="称呼">
        <div class="desc">{{ customerDeatil.appellationDO.typeValue }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="手机">
        <div class="desc">{{ customerDeatil.clueDO.phone }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="微信">
        <div class="desc">{{ customerDeatil.clueDO.weixin }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="年龄">
        <div class="desc">{{ customerDeatil.clueDO.age }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="职业">
        <div class="desc">{{ customerDeatil.clueDO.job || '未知' }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="住址">
        <div class="desc">{{ customerDeatil.clueDO.address }}&nbsp;</div>
      </el-form-item>
      <el-form-item label="填写跟踪记录" prop="noteContent">
        <el-input v-model="customerRemark.noteContent" :rows="8" type="textarea"/>
      </el-form-item>
      <el-form-item label="跟踪方式" prop="noteWay">
        <el-select v-model="customerRemark.noteWay" placeholder="请选择跟踪方式" style="width: 100%"
                   @click="loadDicValue('noteWay')" clearable>
          <el-option v-for="item in noteWayOptions" :key="item.id" :label="item.typeValue" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="clueRemarkSubmit">提 交</el-button>
        <!-- 模仿转换客户按钮，新增加转换为账单按钮，只显示一次 -->
        <el-button type="success" @click="convertBill" v-if="!billConverted">转换为交易</el-button>
        <el-button type="success" plain @click="goBack">返 回</el-button>
      </el-form-item>
    </el-form>

    <!-- 客户备注记录展示 -->
    <el-table :data="customerRemarkList" style="width: 100%">
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column prop="noteWayDO.typeValue" label="跟踪方式"/>
      <el-table-column prop="noteContent" label="跟踪内容"/>
      <el-table-column property="createTime" label="跟踪时间"/>
      <el-table-column property="createByDO.name" label="跟踪人"/>
      <el-table-column property="editTime" label="编辑时间"/>
      <el-table-column property="editByDO.name" label="编辑人"/>
      <el-table-column label="操作">
        <template #default="scope">
          <a href="javascript:" @click="editRemark(scope.row.id)">编辑</a>
          &nbsp;
          <a href="javascript:" @click="delRemark(scope.row.id)">删除</a>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" :page-size="pageSize" :total="total" @current-change="toPage"/>

    <!-- 客户备注编辑弹窗（模仿线索备注编辑弹窗） -->
    <el-dialog
        v-model="customerEditRemarkDialogVisible"
        title="编辑客户跟踪记录"
        width="55%"
        center
        draggable
    >
      <el-form ref="customerRemarkEditForm" :model="customerEditRemarkQuery" label-width="110px"
               :rules="customerEditRemarkRules">
        <el-form-item label="跟踪方式" prop="noteWay">
          <el-select v-model="customerEditRemarkQuery.noteWay" placeholder="请选择跟踪方式" style="width: 100%"
                     @click="loadDicValue('noteWay')" clearable>
            <el-option v-for="item in noteWayOptions" :key="item.id" :label="item.typeValue" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪内容" prop="noteContent">
          <el-input v-model="customerEditRemarkQuery.noteContent" :rows="8" type="textarea"
                    placeholder="请输入跟踪内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="customerEditRemarkDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="customerEditRemarkSubmit">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转换为账单弹窗 -->
    <el-dialog v-model="convertBillDialogVisible" title="转换为账单" width="55%" center>
      <el-form ref="convertBillRefForm" :model="billQuery" label-width="110px" :rules="convertBillRules">
        <el-form-item label="交易金额" prop="money">
          <el-input v-model="billQuery.money" placeholder="请输入交易金额"/>
        </el-form-item>

        <el-form-item label="预计成交日期" prop="expectedDate">
          <el-date-picker
              v-model="billQuery.expectedDate"
              type="datetime"
              style="width: 100%;"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计成交日期"/>
        </el-form-item>

        <!-- 新增：下次联系时间 -->
        <el-form-item label="下次联系时间" prop="nextContactTime">
          <el-date-picker
              v-model="billQuery.nextContactTime"
              type="datetime"
              style="width: 100%;"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择下次联系时间"/>
        </el-form-item>

        <el-form-item label="交易阶段" prop="stage">
          <el-select v-model="billQuery.stage" placeholder="请选择交易阶段" style="width: 100%;" clearable>
            <el-option v-for="item in stageOptions" :key="item.id" :label="item.typeValue" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="交易描述" prop="description">
          <el-input v-model="billQuery.description" type="textarea" :rows="5" placeholder="请输入交易描述"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="convertBillDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="convertBillSubmit">转 换</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.desc {
  background: #fbd1de;
  width: 100%;
  padding-left: 15px;
}
</style>
